import { sleep } from "@/utils";

/** 分页参数 */
type PageQuery = {
  pageNum: number;
  pageSize: number;
  [key: string]: any;
}

export type Options<T> = {
  /** 分页请求API */
  getApi: (
    pagination: AnyObj, 
    query: PageQuery
  ) => Promise<IResData<IResDataInfo<T>>>,

  /** 额外参数 */
  params?: AnyObj,
  /** 额外url参数 */
  _query?: AnyObj,
  /** 成功回调 */
  success?: () => void,
  /** 失败回调 */
  fail?: (err: Error) => void,
  /** 参数处理回调，每次获取列表都会执行 */
  setParams?: () => void,
  /** 重新请求回调 */
  reLoadCallback?: () => void,
}

/**
 * 获取分页列表
 * @param {Options} options
 * @returns
 */
const useList = <T>(options: Options<T>) => {
  const {
    getApi,
    params = {},
    _query = {},
    success = () => {},
    fail = () => {},
    setParams = () => {},
    reLoadCallback = () => {},
  } = options || {};

  /**
   * 请求payload参数
   */
  const pagination = reactive<AnyObj>({ ...params });

  /**
   * url参数
   */
  const query = reactive<PageQuery>({
    pageNum: 1,
    pageSize: 10,
    ..._query
  })

  /**
   * 是否第一次加载
   */
  const isFirst = ref(true);

  /**
   * 加载状态
   */
  const status = ref<LoadingStatus>('normal');

  /**
   * 列表数据
   */
  const list = ref([]) as Ref<T[]>;

  // 当值为 none 时，统一传空字符串表示不限制
  const resetNone = () => {
    for (const key in pagination) {
      const val = pagination[key];
      if (val === 'none') {
        pagination[key] = '';
      }
    }
  }

  /**
   * 获取列表数据
   */
  const getList = async(isReload = false) => {
    try {
      // 加载中或没有更多时不请求
      if (['loading', 'finished'].includes(status.value)) return;

      // 对参数进行处理
      setParams && setParams();
      resetNone();
      status.value = 'loading';

      const { data } = await getApi(pagination, query);
      // await sleep(1000);
      
      if(isReload) {
        const arr = data && (data.records || []);
        list.value = arr;
      } else {
        const arr = data && (data.records || []);
        list.value = list.value.concat(arr);
      }

      // 获取当前数据量
      const currentTotal = query.pageNum * query.pageSize;
      // 数据量与总数对比，得出是否还有更多
      if (currentTotal >= data.total) {
        // 没有更多了
        status.value = 'finished';
      } else {
        // 还有下一页数据
        query.pageNum++;
        status.value = 'more';
      }

      isFirst.value = false;
      success && success();
    } catch (err) {
      isFirst.value = false;
      status.value = 'error';
      fail && fail(err);
    }
  }
  
  /**
   * 重新获取列表数据
   */
  const reLoadList = () => {
    // list.value.length = 0;
    query.pageNum = 1;
    status.value = 'normal';
    reLoadCallback && reLoadCallback();
    getList(true);
  }

  /** 设置payload参数 */
  const setPagination = (data) => {
    Object.assign(pagination, data);
  }
  
  /** 设置url参数 */
  const setQuery = (data) => {
    Object.assign(query, data);
  }

  return {
    list,
    status,
    isFirst,
    pagination,
    query,
    getList,
    reLoadList,
    setQuery,
    setPagination
  }
}

export { useList }
